package com.neu.servlet.snn;

import com.neu.service.snn.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.Map;

@WebServlet(name = "TouXiangServlet", urlPatterns = {"/TouXiangServlet.do"})
@MultipartConfig
public class TouXiangServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String u_id= request.getParameter("u_id");
        Part part = request.getPart("u_touxiang");
        //tomcat8才有这个方法
        //String u_img = part.getSubmittedFileName();
        String fileName=part.getHeader("Content-Disposition");
        String u_img=fileName.substring(fileName.lastIndexOf("."),fileName.length()-1);
        if (".jpg".equals(u_img)||".gif".equals(u_img)) {
            u_img = System.currentTimeMillis() + u_img;
            String path = request.getServletContext().getRealPath("/static/img/images");
            part.write(path + "/" + u_img);
            UserService userService = new UserService();
            HttpSession session = request.getSession();
            boolean flag = userService.doSave(u_img, u_id);
            if (flag) {
                Map<String, Object> user = userService.doFindUserById(u_id);
                session.setAttribute("user", user);
                request.getRequestDispatcher("/WEB-INF/views/user.jsp").forward(request, response);
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
